# coding:utf-8
from numpy import *
import operator
import matplotlib
import matplotlib.pyplot as plt
def classify0(inx,dataSet,labels,k):
    """
    inx:输入数据 array-like
    """
    dataSetSize = dataSet.shape[0]
    # 欧式距离的计算
    #REW:tile:重复这个矩阵(行几遍，列几遍..)
    diffMat = tile(inx,(dataSetSize,1)) -dataSet
    sqDiffMat = diffMat**2
    sq_distances = sqDiffMat.sum(axis=1)
    distances = sq_distances**0.5
    sortedDistIndices = distances.argsort()
    classCount={}
    ###对选取的K个样本所属的类别个数进行统计
    # 选择距离最小的k个点
    for i in range(k):
        voteilabel = labels[sortedDistIndices[i]]
        classCount[voteilabel]=classCount.get(voteilabel,0)+1
    maxcount=0
    ###选取出现的类别次数最多的类别
    for key,value in classCount.items():
        if value > maxcount:
            maxcount=value
            classes=key
    return classes
def autoNorm(dataSet):
    minVals = dataSet.min(0)  # 按特征列选取
    maxVals = dataSet.max(0)
    ranges=maxVals-minVals
    normDataSet=zeros(shape(dataSet))
    m=dataSet.shape[0]
    normDataSet=dataSet - tile(minVals,(m,1))
    normDataSet = normDataSet/tile(ranges,(m,1))
    return normDataSet,ranges,minVals
def datingClassTest():
    hoRatio=0.1
    datingDataMat,datingLabels=fileTomatrix("E:\Type\Media\YData\DataSet\datingTestSet2.txt")
    normMat, ranges, minVals=autoNorm(datingDataMat)
    m = normMat.shape[0]
    numTestVecs=int(m*hoRatio)
    errorCount=0.0
    for i in range(numTestVecs):
        classifierResult=classify0(normMat[i,:],normMat[numTestVecs:m,:],
                                   datingLabels[numTestVecs:m],3)
        print('the classifier came back with: %d,the real answer is: %d' % (classifierResult,datingLabels[i]))
        if (classifierResult != datingLabels[i]): errorCount += 1.0
    print('the total error rate is: %f' % (errorCount/float(numTestVecs)))

def fileTomatrix(filename):
    fr=open(filename)
    arrayOLines=fr.readlines()
    numberOfLines=len(arrayOLines)
    returnMat=zeros((numberOfLines,3))
    classLabelVector=[]
    index=0
    for line in arrayOLines:
        line=line.strip()
        listFromLine=line.split("\t")
        returnMat[index,:]=listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index+=1
    datingDataMat=returnMat
    datingLabels=classLabelVector
    fig = plt.figure()
    ax=fig.add_subplot(111)
    print(len(datingDataMat))
    ax.scatter(datingDataMat[:,0],datingDataMat[:,1],
               15*array(datingLabels),15*array(datingLabels))
    plt.show()
    return returnMat,classLabelVector
    # print(arrayOLines)
#datingClassTest() # REW:约会系统


"""
手写识别系统
32*32像素黑白图像
"""
from pathlib import Path
from os import listdir
# 将图像格式化处理为一个向量。我们将把一个32×32的二进制图像矩阵转换为1×1024的向量，这样前两节使用的分类器就可以处理数字图像信息
def img2vector(filename):
    returnVect = zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0,32*i+j]=int(lineStr[j])
    return returnVect


def handwritingClassTest():
    hwLabels=[]
    trainingFileList = listdir(r"E:\\Type\\Media\\YData\\DataSet\\trainingDigits")
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))
    for i in range(m):
        fileNameStr= trainingFileList[i]
        fileStr=fileNameStr.split(".")[0]
        classNumStr=int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:]=img2vector(f"E:\\Type\\Media\\YData\\DataSet\\trainingDigits\{fileNameStr}")
    testFileList=listdir(r"E:\\Type\\Media\\YData\\DataSet\\testDigits")
    errorCount=0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split(".")[0]
        classNumStr = int(fileStr.split("_")[0])
        vectorUnderTest=img2vector(f"E:\\Type\\Media\\YData\\DataSet\\testDigits\{fileNameStr}")
        classifierResult=classify0(vectorUnderTest,trainingMat,hwLabels,3)
        print('the classifier came back with: %d,the real answer is: %d' % (classifierResult,classNumStr))
        if (classifierResult != classNumStr):errorCount +=1.0
    print('the total number of errors is: %d' % errorCount)
    print('the total error rate is: %f' % (errorCount/float(mTest)))
handwritingClassTest()